import Vue from 'vue'
import Router from 'vue-router'
import Main from './views/main.vue'
import util from './libs/util'

Vue.use(Router)

let routes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login.vue')
    },
    {
        path: '/',
        name: '_home',
        component: Main,
        children: [
            {
                path: '/home',
                name: 'home',
                component: () => import('@/views/home.vue')
            },
            {
                path: '/chat',
                name: 'chat',
                component: () => import('@/views/chat/chat.vue')
            }
        ]
    }
];

const router = new Router({
    routes,
    mode: 'history'
})

router.beforeEach((to, from, next) => {
    const token = util.getWebImUsername()
    if (!token && to.name !== 'login') {
        // 未登录且要跳转的页面不是登录页
        next({
            name: 'login'
        })
    } else if (!token && to.name === 'login') {
        // 未登陆且要跳转的页面是登录页
        next()
    } else if (token && to.name === 'login') {
        // 已登录且要跳转的页面是登录页
        next({
            name: 'home'
        })
    } else {
        next()
    }
})

export default router;
